package com.nifostasky.fragment;
/**
 * 搜索界面
 */

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.nifostasky.comic.ChapterActivity;
import com.nifostasky.comic.R;
import com.nifostasky.entity.SearchInfo;
import com.nifostasky.utils.JsoupContent;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class MainFragment3 extends Fragment {
    private static final File file = new File("data/data/com.nifostasky.comic/cache/info2.txt");
    //声明控件
    private Button mbtn_fragment3 = null;
    private EditText met_fragment3 = null;
    private ListView mlv_search = null;
    private View view  = null;
    //搜索信息
    private List<SearchInfo> listSearchInfo = null;
    //爬取信息
    private JsoupContent jsoupContent = null;
    //适配器
    private Myadapter myAdapter = null;
    //提示框
//    ProgressDialog progreesDiaLog = null;
    /**
     * 获取view界面
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //获取视图
        this.view = inflater.inflate(R.layout.activity_main_fragment3,null);
        //获取控件
        mbtn_fragment3 = view.findViewById(R.id.btn_fragment3);
        met_fragment3 = view.findViewById(R.id.et_fragment3);
        mlv_search = view.findViewById(R.id.lv_search);
        //提取到文本框中
        this.extractFile();
        //实例化爬取类
        jsoupContent = new JsoupContent();
        //设置按键点击事件
        setListeners();


        return view;
    }


    //活动
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    //设置按键点击事件
    private void setListeners(){
        Listener listener = new Listener();
        mbtn_fragment3.setOnClickListener(listener);
    }


    //点击事件实现
    private class Listener implements View.OnClickListener{
        String url = null;
        boolean flag = false;
        int isValid = -1;
        @Override
        public void onClick(View v) {
            Intent intent = null;

            // 按键事件定义
            switch (v.getId()){
                case R.id.btn_fragment3:
                    System.out.println("按键被点击:"+flag + " "+isValid);

//                    MainFragment3.this.setProgressDialog();

                    //获取文本框中的内容
                    url = met_fragment3.getText().toString().trim();
                    //保存到文件中
                    MainFragment3.this.saveFile(url);
                    System.out.println(url);
                    if(TextUtils.isEmpty(url)) {
                        Toast.makeText(view.getContext(), "您的输入不能为空", Toast.LENGTH_SHORT).show();
                        //获取资源成功,关闭提示框
//                        MainFragment3.this.progreesDiaLog.dismiss();
                        break;
                    }

                    //线程获取搜索数据
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            listSearchInfo = jsoupContent.setSearchInfo(url);
                            if(listSearchInfo != null) {
                                isValid = 1;
                                flag = true;

                            }else{
                                isValid = 0;
                                flag = true;
                            }
                            System.out.println("线程结束:"+flag + " "+isValid);
                        }
                    };
                    new Thread(runnable).start();


                    while (true){
                        //System.out.println("循环");
                        if(flag) {
                            while(true) {
                                if (isValid == 1) {
                                /*for(SearchInfo searchInfo :listSearchInfo){
                                    System.out.println(searchInfo.getComicNmae());
                                }*/
                                    this.flag = false;
                                    this.isValid = -1;
                                /*myAdapter = new Myadapter();
                                System.out.println("新建适配器");
                                mlv_search.setAdapter(myAdapter);*/
                                    if (MainFragment3.this.myAdapter == null) {
                                        System.out.println("新建适配器");
                                        myAdapter = new Myadapter();
                                        mlv_search.setAdapter(myAdapter);
                                    } else {
                                        System.out.println("更新数据");
                                        myAdapter.notifyDataSetInvalidated();
                                        //myAdapter.notifyDataSetChanged();
                                    }
                                /*//定义意图并,确定转发位置
                                intent = new Intent();
                                intent.setClass(view.getContext(), ChapterActivity.class);
                                //设置需要传递的参数
                                intent.putExtra("url", url);
                                //执行意图进行跳转
                                System.out.println("按键被点击1");
                                startActivity(intent);*/

                                    //获取资源成功,关闭提示框
//                                    MainFragment3.this.progreesDiaLog.dismiss();
                                    System.out.println("退出:" + flag + " " + isValid);
                                    break;
                                }
                                if (isValid == 0) {
                                    this.flag = false;
                                    this.isValid = -1;
                                    System.out.println("toast中");

                                    Toast.makeText(view.getContext(), "未搜索到信息", Toast.LENGTH_SHORT).show();
                                    //获取资源成功,关闭提示框
//                                    MainFragment3.this.progreesDiaLog.dismiss();
                                    System.out.println("退出:" + flag + " " + isValid);
                                    break;
                                }
                            }
                            if(!flag){
                                break;
                            }
                        }
                    }

                    break;
            }


        }
    }




    //适配器
    private class Myadapter extends BaseAdapter{
        //总共有多少条数据
        @Override
        public int getCount() {
            return listSearchInfo.size();
        }

        //添加数据
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            System.out.println(" 设置内容");
            View view = null;
            if(convertView == null) {
                view = View.inflate(MainFragment3.this.view.getContext(),R.layout.layout2,null);
                //view = new TextView(ChapterActivity.this);
            }else{
                view = convertView;
            }
            //System.out.println(" 设置内容");
            //获取控件
            ImageView iv = view.findViewById(R.id.iv_comicPicture2);
            TextView tv = view.findViewById(R.id.tv_Chaptername2);
            //设置内容 图片和漫画名
            //System.out.println(" 设置内容");
            Glide.with(view.getContext()).load(listSearchInfo.get(position).getPictureAdress()).into(iv);
            tv.setText(listSearchInfo.get(position).getComicNmae());

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(MainFragment3.this.view.getContext(), ChapterActivity.class);
                    intent.putExtra("url",MainFragment3.this.listSearchInfo.get(position).getComicAdress());
                    startActivity(intent);
                }
            });

            return view;
            }


        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }


    }

/*

    //设置消息缓冲提示框
    private void setProgressDialog(){
        //设置缓冲提示框
        progreesDiaLog = new ProgressDialog(view.getContext());
        progreesDiaLog.setTitle("提示");
        progreesDiaLog.setMessage("正在加载");
        progreesDiaLog.setCancelable(false);
        progreesDiaLog.show();
    }

*/

    //保存上次输入的链接,(文件)
    private void saveFile(String serach){
        FileOutputStream fos=null;
        try {
            fos = new FileOutputStream(file);
            fos.write(serach.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fos !=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //将文件提取出来并填入输入框
    private void extractFile(){
        if(file.exists()&&file.length()>0) {
            BufferedReader br = null;
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                br = new BufferedReader(new InputStreamReader(fis));
                String serach = br.readLine();
                met_fragment3.setText(serach);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
